package com.scyshkj.university.wechat.pay;

import com.scyshkj.university.wechat.BeanProvider;
import com.scyshkj.university.wechat.SessionKeys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created by 唐旭 on 2016/11/17.
 */
//@Service
public class WechatLoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        WechatLoginService loginService = BeanProvider.getBean(WechatLoginService.class);
        assert loginService != null;

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpSession session = request.getSession();
        Object attribute = session.getAttribute(SessionKeys.WECHAT_ACCESS_TOKEN);
        if (attribute == null) {
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            response.sendRedirect(loginService.getLoginUrl(request));
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {

    }
}
